package com.lsq.baseadmin.modules.maintenance.utils;

import com.lsq.baseadmin.common.constant.ConstantTask;
import com.lsq.baseadmin.common.enums.SwitchEnum;
import com.lsq.baseadmin.common.utils.ThreadPoolUtil;
import com.lsq.baseadmin.common.utils.ThrowableUtil;
import com.lsq.baseadmin.modules.maintenance.entity.ScheduleJob;
import com.lsq.baseadmin.modules.maintenance.entity.ScheduleJobLog;
import com.lsq.baseadmin.modules.maintenance.mapper.ScheduleJobLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.Future;

/**
 * @author sojan-lsq
 * @since 2020/11/10 18:42
 * @desc
 */
@Slf4j
@Component
public class ExecutionJob extends QuartzJobBean {

//    private ExecutorService service = Executors.newSingleThreadExecutor();

    private ScheduleJobLogMapper scheduleJobLogMapper;
    @Resource
    public void setScheduleJobLogMapper(ScheduleJobLogMapper scheduleJobLogMapper) {
        this.scheduleJobLogMapper = scheduleJobLogMapper;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) {
        ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap()
                .get(ConstantTask.JOB_PARAM_KEY);

        //数据库保存执行记录
        ScheduleJobLog jobLog = new ScheduleJobLog();
        jobLog.setJobId(scheduleJob.getId());
        jobLog.setJobName(scheduleJob.getName());
        jobLog.setBeanName(scheduleJob.getBeanName());
        jobLog.setMethodName(scheduleJob.getMethodName());
        jobLog.setParams(scheduleJob.getParams());

        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            log.info("任务准备执行，任务ID：" + scheduleJob.getId());
            ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(),
                    scheduleJob.getMethodName(), scheduleJob.getParams());
            Future<?> future = ThreadPoolUtil.threadPool.submit(task);

            future.get();

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            jobLog.setTime((int) times);
            //任务状态
            jobLog.setStatus(SwitchEnum.ENABLE.getValue());

            log.info("任务执行完毕，任务ID：" + scheduleJob.getId() + "  总共耗时：" + times + "毫秒");
        } catch (Exception e) {
            log.error("任务执行失败，任务ID：" + scheduleJob.getId(), e);

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            jobLog.setTime((int) times);

            //任务状态
            jobLog.setStatus(SwitchEnum.DISABLE.getValue());
            jobLog.setError(ThrowableUtil.getStackTrace(e));
        } finally {
            scheduleJobLogMapper.insert(jobLog);
        }
    }
}
